
var socket = io('ws://192.168.99.66:3000');
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
var GRID_SIZE = 25; // 单元格的大小
var H_SIZE = null;
var V_SIZE = null;
var color = '';

var checkerboard =[];
var trun = '';
socket.on('conn',function (data) {
    color = data.color;
    document.querySelector('#color').innerHTML = (color==='white'?'白色':"黑色");
    H_SIZE = data.hs;
    V_SIZE = data.vs;
    cvs.width = H_SIZE *GRID_SIZE;
    cvs.height = V_SIZE *GRID_SIZE;
    if(data.num === 2){
      init()
    }
});
socket.on('getCheckBoard',function (data) {

    checkerboard = data.checkerboard;
    trun = data.trun;
    if(color === trun){
        cvs.onclick = putChecs;
    }else{
        cvs.onclick = null;
    }
    drawCheckrboard();
    document.querySelector('#info').innerHTML='现在轮到'+trun+'落子'
});

socket.on('gameover',function (data) {
   document.querySelector('#info').innerHTML = (data ==='black'?'黑棋':'白棋')+'胜';
   cvs.onclick = null
});


function init() {
    if(color === 'null') return;

}

// 放置旗子
function putChecs(e) {
    var x = e.pageX-cvs.offsetLeft;
    var y = e.pageY-cvs.offsetTop;
    x= parseInt(x/GRID_SIZE);
    y= parseInt(y/GRID_SIZE);
    if(checkerboard[x][y].state) return;
    drawArc(x,y);
    socket.emit('putchess',x,y)
}
//画旗子
function drawArc(x,y){
    ctx.beginPath();
    ctx.arc(x * GRID_SIZE + GRID_SIZE / 2,y * GRID_SIZE + GRID_SIZE / 2,(GRID_SIZE / 2)*0.8,0,2 * Math.PI);
    ctx.fillStyle=(checkerboard[x][y].type === 'white' ? 'white':'black');
    ctx.fill();
    ctx.closePath();
}
// 画棋盘
function drawCheckrboard() {
    for(var i=0;i<H_SIZE;i++){
        for (var j = 0;j<V_SIZE;j++) {
            ctx.beginPath();
            ctx.strokeStyle='#000';
            ctx.fillStyle = '#ffc0cb';
            ctx.fillRect(i*GRID_SIZE,j*GRID_SIZE,GRID_SIZE,GRID_SIZE);
            ctx.strokeRect(i*GRID_SIZE,j*GRID_SIZE,GRID_SIZE,GRID_SIZE);
            ctx.closePath()
        }
    }
    console.log(checkerboard)
    for(var i = 0;i<H_SIZE;i++){
        for (var j =0;j<V_SIZE;j++) {

            if(checkerboard[i][j].state) drawArc(i,j)
        }
    }
}